package com.hivekion.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hivekion.common.entity.PagedResultVo;
import com.hivekion.customer.domain.Customer;
import com.hivekion.customer.domain.vo.CustomerViewVo;
import com.hivekion.goods.domain.GoodEntity;
import com.hivekion.goods.domain.vo.CreateGoodInputVo;
import com.hivekion.goods.domain.vo.GoodSearchInputVo;
import com.hivekion.goods.domain.vo.GoodViewVo;
import com.hivekion.goods.mapper.GoodMapper;
import com.hivekion.goods.service.IGoodService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, GoodEntity> implements IGoodService {

    @Resource
    private GoodMapper mapper;

    @Override
    public boolean add(CreateGoodInputVo vo) {
        GoodEntity good = new GoodEntity();
        BeanUtils.copyProperties(vo, good);
        mapper.insert(good);
        return true;
    }

    @Override
    public PagedResultVo<GoodViewVo> getList(GoodSearchInputVo vo) {
        LambdaQueryWrapper<GoodEntity> logLambdaQueryWrapper = Wrappers.lambdaQuery();
        Page<GoodEntity> logPage = new Page<>(vo.getPageNum(), vo.getPageSize());
        logPage.addOrder(new OrderItem("create_time", false));
        IPage<GoodEntity> logPageResult = mapper.selectPage(logPage, logLambdaQueryWrapper);
        List<GoodViewVo> data =
                logPageResult.getRecords().stream()
                        .map(
                                item -> {
                                    GoodViewVo v = new GoodViewVo();
                                    BeanUtils.copyProperties(item, v);
                                    return v;
                                })
                        .collect(Collectors.toList());
        PagedResultVo<GoodViewVo> resultVo =
                new PagedResultVo<GoodViewVo>(
                        vo, (int) logPageResult.getTotal(), data);
        return resultVo;
    }
}
